package jh.com.jhappbf.datamanager;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.ab.activity.AbActivity;
import com.ab.view.titlebar.AbTitleBar;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import androidx.core.content.ContextCompat;
import jh.com.jhappbf.R;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.utils.JsonHelper;
import jh.com.jhappbf.utils.PixAndDpUtil;

/**
 * @author : wwh
 * e-mail : 953889276@qq.com
 * time   : 2018-9-8 15:04:27
 * desc   : 维护cizu表（添加，删除货名，收货，发货，类型，规格，卸货区域等）
 */

public class FieldManagerActivity extends AbActivity implements OnClickListener {
    private EditText editText;
    private Button add;
    private SwipeMenuListView swipeMenuListView;
    private String flag = "";
    private List<String> lists;
    private ArrayAdapter adapter;
    private AbTitleBar mAbTitleBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAbContentView(R.layout.activity_field_manager);
        mAbTitleBar = this.getTitleBar();
        mAbTitleBar.setTitleText("数据管理");
        mAbTitleBar.setLogo(R.drawable.button_selector_back);
        mAbTitleBar.setTitleBarBackgroundColor(ContextCompat.getColor(this, R.color.orange));
        mAbTitleBar.setTitleTextMargin(10, 0, 0, 0);
        mAbTitleBar.setLogoLine(R.mipmap.line);

        initView();
    }

    private void initView() {

        Intent intent = getIntent();
        flag = intent.getStringExtra("flag");
        getFieldValue();
        editText = findViewById(R.id.field_manager_input_edit);
        add = findViewById(R.id.field_manager_input_btn);
        add.setOnClickListener(this);

        swipeMenuListView = findViewById(R.id.field_manager_list);

        swipeMenuListView.setMenuCreator(swipeMenu -> {
            SwipeMenuItem delete = new SwipeMenuItem(FieldManagerActivity.this);
            delete.setBackground(new ColorDrawable(Color.rgb(255, 50, 00)));
            delete.setIcon(R.drawable.history_item_delete);
            delete.setWidth(PixAndDpUtil.dp2px(80, FieldManagerActivity.this));
            swipeMenu.addMenuItem(delete);
        });
        swipeMenuListView.setOnMenuItemClickListener((position, swipeMenu, btnIndex) -> {
            switch (btnIndex) {
                case 0:
                    delete(flag, lists.get(position));
                    break;
                default:
            }
        });
    }

    /**
     * 删除cizu表里的某一条记录
     *
     * @param flag  h(货名)，f(发货)，s(收货),l(类型)等
     * @param value 记录的值
     */
    private void delete(String flag, final String value) {
        String methodName = "deleteField";
        ArrayList<String> params = new ArrayList<>();
        ArrayList<String> values = new ArrayList<>();
        params.add("fieldName");
        params.add("value");
        values.add(flag);
        values.add(value);
        Listener<String> listener = response -> {
            JSONObject object = JsonHelper.getJsonObject(response);
            if (object != null) {
                String result = object.optString("result");
                String memo = object.optString("memo");
                if ("true".equals(result)) {
                    lists.remove(value);
                    adapter.notifyDataSetChanged();
                    Toast.makeText(FieldManagerActivity.this, "删除成功", Toast.LENGTH_SHORT).show();

                } else {
                    Toast.makeText(FieldManagerActivity.this, memo, Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(FieldManagerActivity.this, "删除失败，请重试", Toast.LENGTH_SHORT).show();
            }

        };
        ErrorListener errorListener = volleyError -> Toast.makeText(FieldManagerActivity.this, "网络异常！", Toast.LENGTH_SHORT).show();

        VolleyCallWebService webService = new VolleyCallWebService(methodName, params, values, listener, errorListener, Priority.HIGH);
        VolleySingleton.getVolleyInstance(this).addRequest(webService);
    }

    /**
     * 获取cizu表里所有的货名，收发货，类型等字段
     */
    private void getFieldValue() {
        String methodName = "getFieldValue";
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        param.add("fieldName");
        value.add(flag);
        Listener<String> listener = response -> {
            List<JSONObject> objectList = JsonHelper.getJsonObjects(response);
            lists = new ArrayList<>();
            for (JSONObject object : objectList) {
                lists.add(object.optString("cczz"));
            }
            adapter = new ArrayAdapter(FieldManagerActivity.this, android.R.layout.simple_list_item_1, lists);
            swipeMenuListView.setAdapter(adapter);
        };
        ErrorListener errorListener = volleyError -> Toast.makeText(FieldManagerActivity.this, "网络异常！", Toast.LENGTH_SHORT).show();

        VolleyCallWebService webService = new VolleyCallWebService(methodName, param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(this).addRequest(webService);
    }

    @Override
    public void onClick(View v) {
        addField();
    }

    /**
     * 添加货名收发货等cizu表里的字段
     */
    private void addField() {
        String methodName = "addField";
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        param.add("field");
        param.add("value");
        value.add(flag);
        final String str = editText.getText().toString();
        if (str.length() > 0) {
            value.add(str);
        } else {
            return;
        }

        Listener<String> listener = response -> {
            JSONObject object = JsonHelper.getJsonObject(response);
            if (object != null) {
                String result = object.optString("result");
                String memo = object.optString("memo");
                if ("true".equals(result)) {
                    Toast.makeText(FieldManagerActivity.this, "添加成功！", Toast.LENGTH_SHORT).show();
                    editText.setText("");
                    lists.add(0, str);
                    adapter.notifyDataSetChanged();
                } else {
                    Toast.makeText(FieldManagerActivity.this, memo, Toast.LENGTH_SHORT).show();
                }
            }
        };
        ErrorListener errorListener = volleyError -> Toast.makeText(FieldManagerActivity.this, "网络异常！", Toast.LENGTH_SHORT).show();

        VolleyCallWebService webService = new VolleyCallWebService(methodName, param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(this).addRequest(webService);
    }
}